package com.ruoyi.media.channelsMail.controller;

import java.util.*;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dtflys.forest.http.ForestCookie;
import com.dtflys.forest.http.ForestResponse;
import com.ruoyi.media.forestApi.ChannelsMail;
import com.ruoyi.media.mediaAccount.domain.MediaAccount;
import com.ruoyi.media.mediaAccount.service.IMediaAccountService;
import com.ruoyi.media.utils.WxUtils;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.media.channelsMail.domain.vo.MediaChannelsMailVo;
import com.ruoyi.media.channelsMail.domain.bo.MediaChannelsMailBo;
import com.ruoyi.media.channelsMail.service.IMediaChannelsMailService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 视频号小店开通
 *
 * @author dqw
 * @date 2023-04-01
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/channelsMail/channelsMail")
public class MediaChannelsMailController extends BaseController {

    private final IMediaChannelsMailService iMediaChannelsMailService;

    private final ChannelsMail channelsMail;

    private final IMediaAccountService mediaAccountService;

    /**
     * 查询视频号小店开通列表
     */
    @SaCheckPermission("channelsMail:channelsMail:list")
    @GetMapping("/list")
    public TableDataInfo<MediaChannelsMailVo> list(MediaChannelsMailBo bo, PageQuery pageQuery) {
        return iMediaChannelsMailService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出视频号小店开通列表
     */
    @SaCheckPermission("channelsMail:channelsMail:export")
    @Log(title = "视频号小店开通", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(MediaChannelsMailBo bo, HttpServletResponse response) {
        List<MediaChannelsMailVo> list = iMediaChannelsMailService.queryList(bo);
        ExcelUtil.exportExcel(list, "视频号小店开通", MediaChannelsMailVo.class, response);
    }


    /**
     * 开通视频号小店商品
     */
    @PostMapping("/createShop")
    public R<Void> createShop(@RequestBody MediaChannelsMailBo bo) {
        MediaAccount mediaAccount =  mediaAccountService.getById(bo.getAccountId());
        if (mediaAccount == null) {
            throw new RuntimeException("账号不存在！");
        }
        List<String> ids = new ArrayList<>();
             if(bo.getSpuId().contains(",")){
                 ids = Arrays.asList( bo.getSpuId().split(","));
            }else if(bo.getSpuId().contains("，")){
                 ids =  Arrays.asList( bo.getSpuId().split("，"));
            }else{
                 ids.add(bo.getSpuId());
             }
           for(String id : ids){
               String params = "{\"list\":[{\"spuId\":\""+id+"\",\"ratio\":"+ Integer.parseInt(bo.getRatio()) * 10000 +"}]}";
               String co = mediaAccount.getCookies();
               JSONArray cookiesArr =   JSONArray.parseArray(co);
               String token = "";
               for(int i = 0 ; i < cookiesArr.size();i++){
                   JSONObject data = (JSONObject)cookiesArr.get(i);
                  String data_token = data.getString("name");
                  if(data_token.equals("data_token")){
                      token = data.getString("value");
                  }
               }
               List<ForestCookie> forestCookies = WxUtils.resetForestCookie(co);
               try{
                   String res = channelsMail.batchAddItem(token,params,(request,cookies) -> {
                       cookies.addAllCookies(forestCookies);
                   });
                   System.out.println(res);
               }catch (Exception e){
                   e.printStackTrace();
               }
           }
       return R.ok("添加成功！");
    }




    /**
     * 根据类型选择开通对应的内容
     */
    @PostMapping("/exclusiveInfo")
    public R<Void> exclusiveInfo(@RequestBody MediaChannelsMailBo bo) {
        MediaAccount mediaAccount =  mediaAccountService.getById(bo.getAccountId());
        if (mediaAccount == null) {
            throw new RuntimeException("账号不存在！");
        }
        String co = mediaAccount.getCookies();
        JSONArray cookiesArr =   JSONArray.parseArray(co);
        String token = "";
        for(int i = 0 ; i < cookiesArr.size();i++){
            JSONObject data = (JSONObject)cookiesArr.get(i);
            String data_token = data.getString("name");
            if(data_token.equals("data_token")){
                token = data.getString("value");
            }
        }
        Map<String,Object> params = new HashMap<>();
        params.put("startTime",bo.getStartTime().getTime()/1000);
        params.put("endTime",bo.getEndTime().getTime()/1000);
        params.put("type",bo.getPromotionType());
        params.put("infoList",bo.getInfoList());
        params.put("isConvert",false);
        List<ForestCookie> forestCookies = WxUtils.resetForestCookie(bo.getCookies());
        try{
            String res = channelsMail.getBatchAddExclusiveInfo(token,params,(request,cookies) -> {
                cookies.addAllCookies(forestCookies);
            });
            System.out.println(res);
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.ok("添加成功！");
    }



    /**
     * 开通视频号小店商品
     */
    @PostMapping("/batchAdd")
    public R<Void> batchAdd(@RequestBody MediaChannelsMailBo bo) {
        MediaAccount mediaAccount =  mediaAccountService.getById(bo.getAccountId());
        if (mediaAccount == null) {
            throw new RuntimeException("账号不存在！");
        }
        StringBuilder sb = new StringBuilder();
        String token = "";
        String cookies = mediaAccount.getCookies();
        JSONArray cookiesArr =  JSONArray.parseArray(cookies);
        for(int i = 0 ; i < cookiesArr.size();i++){
            JSONObject data = (JSONObject)cookiesArr.get(i);
            String data_token = data.getString("name");
            if(data_token.equals("data_token")){
                token = data.getString("value");
            }
        }
        List<ForestCookie> forestCookie = WxUtils.resetForestCookie(cookies);
        try{
            String res =  channelsMail.getItemList(token,((forestRequest, forestCookies) -> {
                forestCookies.addAllCookies(forestCookie);
            }));
            JSONObject data = JSONObject.parseObject(res);
            JSONArray jsonArray =  data.getJSONArray("itemList");
            if(jsonArray == null || jsonArray.size() < 1){
                throw new RuntimeException("该账号无商品数据！");
            }
            for(int i = 0 ; i <jsonArray.size();i++){
                JSONObject jsonObject =  (JSONObject) jsonArray.get(i);
                String spuId =  jsonObject.getString("spuId");
                String params = "{\"list\":[{\"spuId\":\""+spuId+"\",\"ratio\":"+ Integer.parseInt(bo.getRatio()) * 10000 +"}]}";
                try{
                    String shopRes = channelsMail.batchAddItem(token,params,(forestRequest,forestCookies) -> {
                        forestCookies.addAllCookies(forestCookie);
                    });
                    JSONObject sd = JSONObject.parseObject(shopRes);
                    String errCode = sd.getString("errCodeList");
                    sb.append("findershop/");
                    sb.append(spuId);
                    if(errCode.equals("[0]")){
                        sb.append("   大哥发财~\r\n");
                    }else{
                        sb.append("   添加失败！\n\n");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.ok(sb.toString());
    }




    /**
     * 获取视频号小店开通详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("channelsMail:channelsMail:query")
    @GetMapping("/{id}")
    public R<MediaChannelsMailVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iMediaChannelsMailService.queryById(id));
    }

    /**
     * 新增视频号小店开通
     */
    @SaCheckPermission("channelsMail:channelsMail:add")
    @Log(title = "视频号小店开通", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody MediaChannelsMailBo bo) {
        return toAjax(iMediaChannelsMailService.insertByBo(bo));
    }

    /**
     * 修改视频号小店开通
     */
    @SaCheckPermission("channelsMail:channelsMail:edit")
    @Log(title = "视频号小店开通", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody MediaChannelsMailBo bo) {
        return toAjax(iMediaChannelsMailService.updateByBo(bo));
    }

    /**
     * 删除视频号小店开通
     *
     * @param ids 主键串
     */
    @SaCheckPermission("channelsMail:channelsMail:remove")
    @Log(title = "视频号小店开通", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iMediaChannelsMailService.deleteWithValidByIds(Arrays.asList(ids), true));
    }
}
